//
//  454. 四数相加II.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/12.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution454 {
    // 初步一想使用一想，使用循环遍历法
    // 但是这样就会是4层for循环
    // a + b + c + d = 0
    // a + b = 0 - (c + d)
    // 将和转换成等式,会收到意想不到的效果
    func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int {
        var dict: [Int:Int] = [:]
        
        for index1 in 0..<nums1.count {
            for index2 in 0..<nums2.count {
                let key = nums1[index1] + nums2[index2]
                if let count = dict[key] {
                    dict[key] = count + 1
                } else {
                    dict[key] = 1
                }
            }
        }

        var count: Int = 0
        
        for item1 in nums3 {
            for item2 in nums4 {
                let key = -(item1 + item2)
                if let indexCount = dict[key] {
                    count += indexCount
                }
            }
        }
        return count
    }
    static func test() {
        let solution = Solution454()
        let nums1 = [1,2]
        let nums2 = [-2,-1]
        let nums3 = [-1,2]
        let nums4 = [0,2]
        let result = solution.fourSumCount(nums1, nums2, nums3, nums4)
        print(result)
    }
}
